import http from '@ohos.net.http';
import util from '@ohos.util';
import Logger from '../utils/Logger'
const TAG = "[HttpStreamService]"
import { bufferToString } from "../utils/fileUtils"
export class HttpStreamService {
  /**
   * HttpRequest对象，承担了发起/取消、订阅响应事件的职责
   */
  private httpClient: http.HttpRequest | undefined = undefined;
  constructor() {
    this.httpClient = http.createHttp();
    this.onHeadersReceive();
    this.onDataReceiveProgress();
  }
  private onHeadersReceive() {
    if (this.httpClient == null) {
      return;
    }
    this.httpClient.on('headersReceive', (header: Object) => {
      console.info(TAG, 'header: ' + JSON.stringify(header));
    });
  }
  public onDataReceive(callback: (result: string) => void) {
    let TAG = "_:_onDataReceive"
    if (this.httpClient == null) {
      return;
    }
    this.httpClient.on('dataReceive', (data: ArrayBuffer) => {
      const str = bufferToString(data)
      callback(str);
    });
  }
  private parseStreamResult(str: string): string {
    let resultArr: Array<string> = str.split('\n');
    console.info(TAG, "resultArr is " + resultArr);
    console.info(TAG, "resultArr is " + resultArr[3]);
    if (resultArr[3] == null) {
      return "";
    }
    let result = JSON.parse(resultArr[3].slice(5));
    let resultStr = result.output.choices[0].message.content
    return resultStr;
  }
  private onDataReceiveProgress() {
    if (this.httpClient == null) {
      return;
    }
    this.httpClient.on('dataReceiveProgress', (data: Data) => {
      console.log(TAG, "dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
    });
  }
  private onDataEnd() {
    if (this.httpClient == null) {
      return;
    }
    this.httpClient.on('dataEnd', () => {
      console.info(TAG, 'No more data in response, data receive end');
    });
  }
  public destroy() {
    if (this.httpClient == null) {
      return;
    }
    this.httpClient.off('headersReceive');
    this.httpClient.off('dataReceive');
    this.httpClient.off('dataReceiveProgress');
    this.httpClient.off('dataEnd');
    this.httpClient.destroy();
  }
  async requestHttp(url: string, requestOption: http.HttpRequestOptions): Promise<number> {
    console.info(TAG, "start request:" + JSON.stringify(requestOption));
    if (this.httpClient == null) {
      return http.createHttp().requestInStream(url, requestOption);
    } else {
      return this.httpClient.requestInStream(url, requestOption);
    }
  }
}
class Data {
  receiveSize: number = 0;
  totalSize: number = 0;
}
let httpStreamService: HttpStreamService = new HttpStreamService();
export default httpStreamService
